<?php
namespace app\app\controller;


use app\common\model\Comment;
use app\common\model\Message;
use app\common\model\TopicArticle;
use think\Db;
use think\Exception;

class Share extends Base
{

    /**
     * 添加分享
     * @return \think\response\Json
     */
    public function add(){
        try{
            Db::startTrans();
            $input = input('post.',null,'trim');
            $input['parent_id'] = $this->parent_id;
            $input['type'] = 3;
            $input['is_show'] = 1;

            $data = new \app\common\model\Article();
            $data->allowField(true)->force()->save($input);

            //关联表
            $topic = $input['topicList'];
            if(!empty($topic)){
                $topic_array = explode(',',$topic);
                foreach ($topic_array as $v){
                    $model = new TopicArticle();
                    $model->topic_id = $v;
                    $model->article_id = $data['id'];
                    $model->save();
                }
            }

            //message
            $follow = \app\common\model\Follow::where(['type'=>1,'parent_id'=>$input['parent_id']])->column('operate_id');
            if(!empty($follow)){
                foreach ($follow as  $v){
                    $message = new Message();
                    $message->type = 3;
                    $message->parent_id = $v;
                    $message->operate_id = $input['parent_id'];
                    $message->relate_id = $data['id'];
                    $message->save();
                }
            }
            Db::commit();
            return $this->succeed('分享成功',[]);
        }catch (Exception $e){
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }


    /**
     * Notes:分享内容详情
     * Date: 2020/10/3
     * Time: 14:46
     * @return \think\response\Json
     * @throws \Exception
     */
    public function detail(){
        try{
            $input['parent_id'] = $this->parent_id;
            $input['id'] = input('post.id',null,'trim');
            $list = \app\common\model\Article::getList($input);
            if($list['code'] == 1){
                \exception($list['msg']);
            }
            if(empty($list['data'])){
                \exception('信息不存在');
            }
            $detail = $list['data'][0];
            $comment = Comment::getList(['related_id'=>$detail['id'],'parent_id'=>$this->parent_id]);
            if($comment['code'] == 1){
                \exception($comment['msg']);
            }
            return $this->succeed('分享成功',['data'=>$detail,'comment'=>$comment['data']]);
        }catch (Exception $e){
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }
}
